<template>
  <view class="container">
    <!-- 顶部组件 -->
    <u-navbar
      :is-back="true"
      :background="{ background: 'transparent' }"
      :border-bottom="false"
      id="nav-bar"
      title="登录"
    ></u-navbar>
    <image class="bg" src="/static/images/bg.png" mode="widthFix"> </image>
    <view class="content">
      <view class="welcome">
        <view class="text">欢迎来到汇数生活</view>
      </view>
      <view class="tabs">
        <view
          class="tab"
          :class="{ 'tab-active': currentTab === 0 }"
          @click="tabChange(0)"
          >验证码登录</view
        >
        <view
          class="tab"
          :class="{ 'tab-active': currentTab === 1 }"
          @click="tabChange(1)"
          >密码登录</view
        >
      </view>
      <view class="formBox">
        <view class="form-item">
          <text class="label">账号</text>
          <u-input
            v-model="form.phone"
            class="input"
            placeholder="请输入您的账号"
            @input="phoneInput"
          />
        </view>

        <view v-if="currentTab === 1" class="form-item mt30">
          <text class="label">密码</text>
          <u-input
            v-model="form.password"
            class="input"
            type="password"
            placeholder="请输入您的密码"
            @input="passwordInput"
          />
        </view>

        <view v-else class="form-item mt30">
          <text class="label">验证码</text>
          <u-input
            v-model="form.code"
            class="input"
            type="password"
            placeholder="请输入收到的验证码"
            @input="codeInput"
          />
          <view slot="right" class="sendCodeBtn" @click="getCode">{{
            codeTips
          }}</view>
        </view>
      </view>
      <view
        class="login margin-top-50"
        :class="canSubmit ? 'active' : ''"
        @click="submit"
      >
        登录
      </view>

      <view class="btn-group">
        <view class="btn-item" @click="navigateTo('/pages/login/register')">
          注册账号
        </view>
        <view class="btn-item" @click="navigateTo('/pages/login/forget')">
          忘记密码
        </view>
      </view>
    </view>
    <view class="agreement">
      <view class="agreement-in">
        <u-checkbox
          v-model="check"
          size="30rpx"
          active-color="#B7926E"
          label-disabled
          @change="checkboxChange"
        >
          <view class="agreement-text">
            已阅读并同意
            <text
              @click="
                navigateTo('/pages/agree/index?title=隐私保护协议&type=1')
              "
              >《用户服务与隐私保护协议》
            </text>
          </view>
        </u-checkbox>
      </view>
    </view>
  </view>
</template>

<script>
import { memberLogin, getMemberInfo } from '@/api/login';
import service from '@/common/service.js';
import util from '@/common/utils.js';
import md5 from '@/common/md5.js'; //md5加密
// #ifdef APP-PLUS
// const jyJPush = uni.requireNativePlugin('JY-JPush');
// #endif

export default {
  data() {
    return {
      form: { phone: '', password: '', code: '' },
      check: false,
      checkRemember: true,
      canSubmit: false,
      currentTab: 0,
      codeTips: '获取验证码',
    };
  },
  onLoad() {
    const userName = uni.getStorageSync('userName'),
      psw = uni.getStorageSync('psw');
    if (userName) {
      this.form.phone = userName;
    }
    if (psw) {
      this.form.password = psw;
    }
  },
  methods: {
    navigateTo(url) {
      uni.navigateTo({
        url: url,
      });
    },
    tabChange(index) {
      this.currentTab = index;
    },
    codeChange(text) {
      this.codeTips = text;
    },
    phoneInput(value) {
      this.setSubmitBtnStatus();
    },
    codeInput(value) {},
    passwordInput(value) {
      this.setSubmitBtnStatus();
    },
    // 获取验证码
    getCode() {
      if (this.$refs.uCode.canGetCode) {
        if (!this.form.phone) {
          util.showToast('手机号不能为空');
          return;
        }
        if (!util.checkPhone(this.form.phone)) {
          util.showToast('手机号格式有误');
          return;
        }
        uni.showLoading({
          title: '正在获取验证码',
        });
        const that = this;
        const params = {
          phone: that.form.phone,
        };
        service.sendForgetPwdSmsCode(
          params,
          function (res) {
            if (res && res.data) {
              uni.hideLoading();
              util.showToast('验证码已发送');
              that.$refs.uCode.start();
            } else {
              util.showToast(res.message || '发送失败');
            }
          },
          function (res) {
            util.showToast(res.message || '发送失败');
          }
        );
      } else {
        util.showToast('倒计时结束后再发送');
      }
    },
    checkboxChange(e) {
      this.check = e.value;
      this.setSubmitBtnStatus();
    },
    checkboxRememberChange(e) {
      this.checkRemember = e.value;
    },
    setSubmitBtnStatus() {
      if (!this.check) {
        this.canSubmit = false;
        return;
      }
      if (!this.form.phone) {
        this.canSubmit = false;
        return;
      }
      if (!this.form.password) {
        this.canSubmit = false;
        return;
      }
      this.canSubmit = true;
    },
    checkValue() {
      if (!this.check) {
        util.showToast('请先阅读并同意协议');
        return false;
      }
      if (!this.form.phone) {
        util.showToast('账号不能为空');
        return false;
      }
      // if (!util.checkPhone(this.form.phone)) {
      //   util.showToast("手机号格式有误");
      //   return false;
      // }
      if (!this.form.password) {
        util.showToast('密码不能为空');
        return false;
      }
      return true;
    },
    submit() {
      if (!this.checkValue()) {
        return;
      }
      uni.showLoading({
        title: '正在登录',
      });
      const that = this;
      const params = {
        userName: that.form.phone,
        pwd: md5.md5(that.form.password),
      };
      memberLogin(params)
        .then((res) => {
          uni.hideLoading();
          if (res && res.data) {
            const { data } = res;
            uni.setStorageSync('userName', that.form.phone);
            uni.setStorageSync('psw', that.form.password);
            uni.setStorageSync('token', data.token); //存储token
            // that.getMyInfo();
            util.showToast('登录成功，正在跳转');
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/home/index',
              });
            }, 1500);
          } else {
            util.showToast(res.message || '登录失败');
          }
        })
        .catch((err) => {
          uni.hideLoading();
          util.showToast(err.message || '登录失败');
        });
    },
    // getMyInfo() {
    //   const that = this;
    //   getMemberInfo({})
    //     .then((res) => {
    //       if (res && res.status === 1) {
    //         uni.setStorageSync('userInfo', res.data);
    //         const userId = res.data.id.toString() || '';
    //         uni.getSystemInfo({
    //           success: function (res) {
    //             if (res.platform == 'ios') {
    //               that.setAlias(userId);
    //               that.watchPush();
    //               that.watchPushClick();
    //             } else {
    //               that.initJyJPush(that, userId);
    //             }
    //           },
    //           fail: function (res) {
    //             console.error(res);
    //           },
    //         });
    //       } else {
    //         util.showToast(res.message);
    //       }
    //     })
    //     .catch((err) => {});
    // },
    // initJyJPush(that, userId) {
    //   //初始化成功
    //   jyJPush.android_init((res) => {
    //     setTimeout(() => {
    //       that.setAlias(userId);
    //     }, 1000 * 20);
    //     that.watchPush();
    //     that.watchPushClick();
    //   });
    // },
    // //设置别名
    // setAlias(userId) {
    //   jyJPush.setJYJPushAlias({ userAlias: userId }, (result) => {
    //     console.log('setJYJPushAlias', JSON.stringify(result));
    //   });
    // },
    // //监听消息推送事件
    // watchPush() {
    //   jyJPush.addJYJPushReceiveNotificationListener((result) => {
    //     //  监听成功后，若收到推送，会在result返回对应的数据；数据格式保持极光返回的安卓/iOS数据一致
    //     console.log(' watchPush result', result);
    //   });
    // },
    // //监听推送点击事件
    // watchPushClick() {
    //   jyJPush.addJYJPushReceiveOpenNotificationListener((result) => {
    //     //  监听成功后，若点击推送消息，会触发result；数据格式保持极光返回的安卓/iOS数据一致
    //     console.log(' ClickPush result', result);
    //     try {
    //       let notificationExtras = {};
    //       if (Object.prototype.toString.call(result) === '[object Object]') {
    //         notificationExtras = result;
    //       } else {
    //         notificationExtras = JSON.parse(result.notificationExtras);
    //       }
    //       if (notificationExtras && notificationExtras.url) {
    //         uni.navigateTo({
    //           url: notificationExtras.url,
    //         });
    //       }
    //     } catch (error) {
    //       console.error(error);
    //     }
    //   });
    // },
  },
};
</script>

<style lang="scss">
.container {
  position: relative;
  width: 100%;
  min-height: 100vh;
  background: #f5f5f5;
  .bg {
    position: fixed;
    top: 0;
    width: 100%;
    height: auto;
    z-index: 1;
  }
  .agreement {
    position: absolute;
    left: 0;
    bottom: 60rpx;
    width: 100%;
    padding: 0 20rpx;
    z-index: 99;
    .agreement-in {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      width: 100%;
      text-align: center;
    }
    .agreement-text {
      font-size: 22rpx;
      font-weight: normal;
      color: #999999;
      line-height: 1;
      text {
        color: #b7926e;
      }
    }
  }
}

.content {
  position: relative;
  width: 100%;
  padding: 140rpx 50rpx 0;
  z-index: 99;
  .welcome {
    position: relative;
    display: inline-block;
    .text {
      font-size: 42rpx;
      font-weight: bold;
      color: #222222;
      line-height: 1;
      z-index: 99;
    }
  }

  .tabs {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    margin-top: 90rpx;
    width: 100%;
    .tab {
      padding: 0 20rpx;
      font-family: PingFang SC, sans-serif;
      font-weight: 400;
      font-size: 28rpx;
      color: #333333;
      line-height: 32rpx;
    }
    .tab-active {
      font-weight: bold;
      font-size: 32rpx;
    }
  }

  .formBox {
    margin-top: 40rpx;
    width: 100%;
    .form-item {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      position: relative;
      width: 100%;
      height: 88rpx;
      padding: 0 30rpx 0 138rpx;
      background-color: #ffffff;
      border: 1px solid #f0f0f0;
      border-radius: 20rpx;
      ::v-deep {
        .u-form-item--left {
          width: 0;
          flex: 0;
        }
      }
      .label {
        position: absolute;
        left: 0;
        top: 50%;
        padding-right: 20rpx;
        transform: translateY(-50%);
        width: 120rpx;
        font-family: PingFang SC, sans-serif;
        font-weight: bold;
        font-size: 30rpx;
        color: #222222;
        line-height: 32rpx;
        text-align: right;
        border-right: 1px solid #cccccc;
      }

      .input {
        flex: 1;
      }
    }

    .sendCodeBtn {
      width: 180rpx;
      font-size: 30rpx;
      font-weight: normal;
      color: #b7926e;
      text-align: right;
    }
  }

  .btn-group {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    margin-top: 40rpx;
    width: 100%;
    .btn-item {
      padding: 0 20rpx;
      font-size: 28rpx;
      font-weight: normal;
      color: #b7926e;
      line-height: 28rpx;
      cursor: pointer;
      &:last-child {
        border-left: 1rpx solid #b7926e;
      }
    }
  }

  .login {
    margin-top: 40rpx;
    height: 88rpx;
    line-height: 88rpx;
    font-size: 28rpx;
    font-weight: normal;
    color: #ffffff;
    background: #e7e7e7;
    border-radius: 20rpx;
    text-align: center;
  }

  .active {
    background: linear-gradient(90deg, #332108, #201403);
  }
}
</style>
